package com.jacklin.controller;

import com.jacklin.DTO.OrderDTO;
import com.jacklin.enums.ResultEnum;
import com.jacklin.exception.MyException;
import com.jacklin.service.OrderService;
import com.jacklin.service.PayService;
import com.lly835.bestpay.model.PayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 发起支付
 *
 * @Author 林必昭
 * @Date 2019/4/18 21:44
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayService payService;

    /**
     * 这里要传俩个参数：orderId和returnUrl
     * 访问方式：127.0.0.1/newstarsell/pay/create?orderId=...&returnUrl=...
     * @param orderId
     * @param returnUrl
     * @return
     */
    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String,Object> map){

        //1.查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if (orderDTO==null){
            throw new MyException(ResultEnum.ORDER_NOT_EXIST);
        }

        //发起支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("payResponse",payResponse);


        return new ModelAndView("pay/create",map);
    }

    /**
     * 微信支付异步通知
     * @return
     */

    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData){
        payService.notify(notifyData);

        //支付完成，返回微信处理结果
        return new ModelAndView("pay/success");


    }
}
